<template>
    <div class="wrap edu-page-warp">
        <InnerBreadcrumb v-model="pageIndex" :path="breadPath"></InnerBreadcrumb>
        <div v-show="pageIndex === 1">
            <ConditionCard
                shadow="never"
                body-style="padding: 16px 16px 6px 16px;"
                @search="query"
                @reset="reset"
            >
                <el-form
                    :model="condition"
                    label-position="right"
                    label-width="100px"
                    ref="conditionForm"
                    label-suffix="："
                    :rules="rules"
                >
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('sqlLog.serviceName')" prop="serviceName">
                                <el-select
                                    v-model="condition.serviceName"
                                    style="width: 100%"
                                    filterable
                                    clearable
                                >
                                    <el-option
                                        v-for="item in options.serviceNames"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('message.startTime')"
                                class="no-bottom"
                                prop="startTime"
                            >
                                <el-date-picker
                                    v-model="condition.startTime"
                                    :picker-options="pickerOptions"
                                    type="datetime"
                                    :placeholder="$t('message.plsSelect') + $t('message.startTime')"
                                    format="yyyy/MM/dd HH:mm:ss"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    align="right"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                :label="$t('message.endTime')"
                                class="no-bottom"
                                prop="endTime"
                            >
                                <el-date-picker
                                    v-model="condition.endTime"
                                    :picker-options="pickerOptions"
                                    type="datetime"
                                    :placeholder="$t('message.plsSelect') + $t('message.endTime')"
                                    format="yyyy/MM/dd HH:mm:ss"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    align="right"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <!-- <el-col :span="8">
                            <el-form-item :label="$t('sqlLog.dept')" prop="dept">
                                <el-select v-model="condition.dept" style="width: 100%" filterable  clearable>
                                    <el-option
                                        v-for="item in options.dept"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="8">
                            <el-form-item :label="$t('sqlLog.ip')" prop="ip">
                                <el-input
                                    clearable
                                    v-model="condition.ip"
                                    :placeholder="$t('sqlLog.ph_ip')"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('sqlLog.user')" prop="user" clearable>
                                <el-input
                                    v-model="condition.user"
                                    :placeholder="$t('sqlLog.ph_user')"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('sqlLog.type')" prop="type">
                                <el-select v-model="condition.type" style="width: 100%" clearable>
                                    <el-option
                                        v-for="item in options.type"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('sqlLog.content')" prop="content">
                                <el-input
                                    v-model="condition.content"
                                    clearable
                                    :placeholder="$t('sqlLog.ph_content')"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </ConditionCard>
            <el-card shadow="never" body-style="padding: 24px;">
                <el-row class="edu-opertion-bar" type="flex" justify="space-between" align="middle">
                    <el-col class="edu-page-title mg-top">{{ $t('sqlLog.logList') }}</el-col>
                    <el-col style="color: blue; text-align: right" plain>
                        {{ '从 ' + timeStr.startStr + ' 到 ' + timeStr.endStr + ' 止' }}
                    </el-col>
                </el-row>
                <el-table :data="tableData" style="width: 100%" stripe tooltip-effect="light">
                    <el-table-column
                        :label="$t('sqlLog.serviceName')"
                        width="150"
                        show-overflow-tooltip
                    >
                        <template slot-scope="props">
                            {{ props.row.serviceName }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column :label="$t('sqlLog.userId')" show-overflow-tooltip>
                        <template slot-scope="props">
                            {{ props.row.userId }}
                        </template>
                    </el-table-column> -->
                    <el-table-column
                        :label="$t('sqlLog.userName')"
                        width="80"
                        show-overflow-tooltip
                    >
                        <template slot-scope="props">
                            {{ props.row.userName }}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column :label="$t('sqlLog.dept')" show-overflow-tooltip>
                        <template slot-scope="props">
                            {{ props.row.dept }}
                        </template>
                    </el-table-column> -->
                    <el-table-column :label="$t('sqlLog.type')" width="80">
                        <template slot-scope="props">
                            {{ props.row.type === 0 ? '查询' : '更新' }}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('sqlLog.ip')" width="150" show-overflow-tooltip>
                        <template slot-scope="props">
                            {{ props.row.ip }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        :label="$t('sqlLog.createTime')"
                        width="160"
                        show-overflow-tooltip
                    >
                        <template slot-scope="props">
                            {{ props.row.createTime }}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('sqlLog.content')" show-overflow-tooltip>
                        <template slot-scope="props">
                            {{ props.row.content }}
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('message.operating')" width="50">
                        <template slot-scope="scope">
                            <el-button type="text" @click="getDetailById(scope.row.id)" size="mini">
                                {{ $t('message.detail') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="edu-pagination">
                    <div class="float-right">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page.pageNum_"
                            :page-sizes="[10, 20, 40, 80, 100]"
                            :page-size="page.pageSize_"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="page.total_"
                            style="float: right; margin-top: 10px"
                        ></el-pagination>
                    </div>
                </div>
            </el-card>
        </div>
        <logDetail
            v-show="pageIndex === 2"
            style="height: calc(100% - 24px)"
            @backToLog="backToLog"
            :detailData="sqlLog"
        ></logDetail>
    </div>
</template>
<script>
import { getSqlLogDetail, getSqlLogList, getSqlLogTime } from 'common/src/api/sqlLog'
import { getAllCollege } from 'common/src/api/user'
import { queryDic } from 'common/src/api/dictionary'
import UTILS from 'common/src/utils/utils'
import LogDetail from './logDetail'
export default {
    name: 'sqlLog',
    components: {
        LogDetail,
    },
    data() {
        var timeRange = 7 * 24 * 60 * 60 * 1000
        var startTimeRule = (rule, value, callback) => {
            if (!value) callback(new Error('请选择开始时间'))
            if (this.condition.endTime && value > this.condition.endTime ) {
                callback(new Error(this.$t("examinationLevel.timeError")));
            } else if( new Date(this.condition.endTime).getTime() - new Date(value).getTime() >
                timeRange){
                callback(new Error('开始和结束时间最多相差7天'))
                }else {
                callback();
            }
        }
        var endTimeRule = (rule, value, callback) => {
            if (!value) callback(new Error('请选择结束时间'))
            if (this.condition.startTime && this.condition.startTime > value ) {
                callback(new Error(this.$t("examinationLevel.timeError")));
            } else if(
                new Date(value).getTime() - new Date(this.condition.startTime).getTime() >
                timeRange
            ){
                callback(new Error('开始和结束时间最多相差7天'))
            } {
                callback();
            }
        }
        return {
            pageIndex: 1,
            breadPath: {
                label: 'sql日志',
                key: 1,
                children: [
                    {
                        key: 2,
                        label: '',
                    },
                ],
            },
            page: {
                pageNum_: 1,
                pageSize_: 10,
                total_: 0,
            },
            condition: {
                serviceName: '',
                startTime: '',
                endTime: '',
                dept: '',
                user: '',
                type: '',
                ip: '',
                content: '',
            },
            timeStr: {
                startStr: '',
                endStr: '',
            },
            sqlLog: {},
            //不能写大括号，神坑
            tableData: [],
            options: {
                type: [
                    //操作類型
                    {
                        value: 0,
                        label: '查询',
                    },
                    {
                        value: 1,
                        label: '更新',
                    },
                ],
                dept: [],
                serviceNames: [],
            },
            pickerOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date())
                        },
                    },
                    {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() - 3600 * 1000 * 24)
                            picker.$emit('pick', date)
                        },
                    },
                    {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date()
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                            picker.$emit('pick', date)
                        },
                    },
                ],
            },
            rules: {
                startTime: [
                    {
                        validator: startTimeRule,
                        trigger: 'blur',
                    },
                ],
                endTime: [
                    {
                        validator: endTimeRule,
                        trigger: 'blur',
                    },
                ],
            },
        }
    },
    methods: {
        async getSqlLogList(data) {
            try {
                let resp = await getSqlLogList(data)
                if (resp && resp.code == 200) {
                    if (resp && resp.data && resp.code == 200) {
                        let data = resp.data.list || []
                        this.tableData = data.map((item) => {
                            let {
                                id,
                                serviceName,
                                startTime,
                                endTime,
                                createTime,
                                manageDptI18n: dept,
                                userId,
                                userName,
                                opType: type,
                                ip,
                                content,
                            } = item
                            return {
                                id,
                                serviceName,
                                startTime,
                                endTime,
                                createTime,
                                dept,
                                userId,
                                userName,
                                type,
                                ip,
                                content,
                            }
                        })
                        this.page.pageNum_ = resp.data.pageNum_
                        this.page.pageSize_ = resp.data.pageSize_
                        this.page.total_ = resp.data.total_
                    }
                }
            } catch (error) {
                console.log(error)
            }
        },
        async getSqlLogDetail(id) {
            try {
                let resp = await getSqlLogDetail(id)
                if (resp && resp.code == 200) {
                    let {
                        id,
                        serviceName,
                        startTime,
                        endTime,
                        createTime,
                        manageDptI18n: dept,
                        userId,
                        userName,
                        opType: type,
                        ip,
                        content,
                    } = resp.data
                    this.sqlLog = {
                        id,
                        serviceName,
                        startTime,
                        endTime,
                        dept,
                        userId,
                        userName,
                        type,
                        ip,
                        content,
                        createTime,
                    }
                    this.sqlLog.type = this.sqlLog.type === 0 ? '查询' : '更新'
                }
            } catch (error) {
                console.log(error)
            }
        },
        async getSqlLogTime() {
            try {
                let resp = await getSqlLogTime()
                if (resp && resp.code == 200) {
                    if (!resp.data) return
                    this.timeStr = resp.data
                    this.timeStr.startStr = this.timeStr.startTime.substr(0, 19)
                    this.timeStr.endStr = this.timeStr.endTime.substr(0, 19)
                }
            } catch (error) {
                console.log(error)
            }
        },
        async getAllCollege() {
            try {
                let resp = await getAllCollege(0, 1, 1)
                if (resp && resp.code == 200 && resp.data) {
                    for (const item of resp.data) {
                        this.options.dept.push({
                            label: item.deptName,
                            value: item.deptCode,
                        })
                    }
                }
            } catch (error) {
                console.log(error)
            }
        },
        async getServiceNames() {
            try {
                let resp = await queryDic({
                    keys: ['X_WFWMC'],
                    type: 'allChild',
                })
                if (resp && resp.code === 200) {
                    UTILS.fillSelect(
                        {
                            serviceNames: 'X_WFWMC',
                        },
                        resp.data,
                        this.options
                    )
                }
            } catch (error) {
                console.log(error)
            }
        },
        initOption() {
            this.getAllCollege()
            this.getServiceNames()
        },
        getOperationTypeStr(val) {
            if (val == 'I') return '添加'
            else if (val == 'D') return '删除'
            else if (val == 'U') return '修改'
            else if (val == 'R') return '查询'
            else return ''
        },
        getDetailById(id) {
            this.pageIndex = 2
            this.breadPath.children[0].label = `详情`
            this.getSqlLogDetail(id)
        },

        getTimeStr() {
            this.getSqlLogTime()
        },

        getAuditLogInfo() {
            let {
                serviceName,
                startTime,
                endTime,
                dept: manageDpt,
                userId: user,
                type: opType,
                ip,
                content,
            } = this.condition
            let query = {
                pageSize_: this.page.pageSize_,
                pageNum_: this.page.pageNum_,
                serviceName,
                startTime,
                endTime,
                manageDpt,
                user,
                opType,
                ip,
                content,
            }
            this.getSqlLogList(query)
            this.getTimeStr()
        },
        handleSizeChange(val) {
            this.page.pageSize_ = val
            this.getAuditLogInfo()
        },
        handleCurrentChange(val) {
            this.page.pageNum_ = val
            this.getAuditLogInfo()
        },
        reset() {
            this.$refs.conditionForm.resetFields()
            this.query()
        },
        query() {
            this.$refs.conditionForm.validate((valid) => {
                if (valid) {
                    this.getAuditLogInfo()
                }
            })
        },
        backToLog() {
            this.pageIndex = 1
        },
    },
    created() {
        this.initOption()
    },
    mounted() {
        this.getAuditLogInfo()
    },
    watch: {
        pageIndex(val) {
            if (val === 1) {
            }
        },
    },
}
</script>
<style lang="scss" scoped>
.wrap {
    height: calc(100% - 8px);
}
</style>
